<template>
	<a-spin :spinning="loading">
		<section class="flex items-center justify-between mb-16">
			<section class="flex items-center">
				<span class="label">账号邮箱：</span>
				<a-input @keyup.enter="search" style="width: 300px;" allow-clear placeholder="请输入账号或者邮箱" :max-length="100" v-model="searchInp"/>
				<a-button class="mx-8" type="primary" @click="search">查询</a-button>
				<a-button @click="reset">重置</a-button>
			</section>
			<a-button v-if="$permissionJudge('UserCreate')" @click="showModal = true" type="primary" icon="plus">新建</a-button>
		</section>
		<a-table
			row-key="id"
			:columns="columns"
			:data-source="data"
			:pagination="pagination"
		>
			<template #enable="val, data">
				<section @click.stop>
					<a-switch v-if="$permissionJudge('SetUserStatus')" :disabled="data.isSystemUser" :checked="data.isStop === 0" @change="setUserStop(data)"/>
				</section>
			</template>
			<template #action="val, data, index">
				<a
					href="javascript:;"
					:class="{
            'gray': data.isSystemUser,
            'cursor-not-allowed': data.isSystemUser
          }"
					@click="editUser(data)"
					v-if="$permissionJudge('UserUpdate')"
				>编辑</a>
				<a-divider v-if="$permissionJudge('UserUpdate') && $permissionJudge('UserDelete')" type="vertical"/>
				<a
					href="javascript:;"
					:class="{
            'gray': data.isSystemUser,
            'red': !data.isSystemUser,
            'cursor-not-allowed': data.isSystemUser
          }"
					v-if="$permissionJudge('UserDelete')"
					@click="removeUser(data, index)"
				>删除</a>
			</template>
		</a-table>
		<a-modal
			v-model="showModal"
			width="1000px"
			:title="`${isEdit ? '修改信息' : '新建用户'}`"
			:confirm-loading="loading"
			@cancel="cancel"
			@ok="confirmUser"
		>
			<a-form v-if="showModal" :form="form">
				<a-row type="flex" :gutter="16">
					<a-col :span="18">
						<a-row :gutter="16">
							<a-col :span="12">
								<a-form-item label="账户名">
									<a-input
										placeholder="请输入账户名"
										:max-length="16"
										:disabled="isEdit"
										v-decorator="[
                      'account',
                      {rules: [{required: true, whitespace: true, message: '请输入账户名'}]}
                    ]"
									/>
									<a-input type="hidden" v-decorator="['id']"/>
									<a-input type="hidden" v-decorator="['imagePath', {initialValue: ''}]"/>
									<a-input type="hidden" v-decorator="['thumbnailPath', {initialValue: ''}]"/>
								</a-form-item>
							</a-col>
							<a-col :span="12">
								<a-form-item label="邮箱">
									<a-input
										placeholder="请输入邮箱"
										auto-complete="off"
										:max-length="30"
										v-decorator="[
                      'email',
                      {
                        rules: [{required: true, whitespace: true, type: 'email', message: '请输入正确的邮箱'}],
                        initialValue: '',
                        validateTrigger: 'blur'
                      }
                    ]"
									/>
								</a-form-item>
							</a-col>
							<a-col :span="12">
								<a-form-item label="联系电话">
									<a-input
										placeholder="请输入联系电话"
										:max-length="15"
										v-decorator="[
                      'phone',
                      {rules: [{required: true, validator: $utils.phoneValidator}]}
                    ]"
									/>
								</a-form-item>
							</a-col>
							<a-col :span="12">
								<a-form-item label="登录密码">
									<a-input-password
										:maxlength="50"
										placeholder="若要设置请填入，否则将不会更新"
										type="password"
										autocomplete="off"
										v-decorator="[
                      'password',
                      {
                        rules: [{required: !isEdit, validator: passwordValidator}],
                        initialValue: ''
                      }
                    ]"
									/>
								</a-form-item>
							</a-col>
							<a-col v-if="!isEdit" :span="12">
								<a-form-item label="确认登录密码">
									<a-input-password
										:maxlength="50"
										placeholder="若要设置请填入，否则将不会更新"
										type="password"
										v-decorator="[
                      'confirmPassword',
                      {rules: [{required: true, validator: confirmPasswordValidator}], initialValue: ''}
                    ]"
									/>
								</a-form-item>
							</a-col>
							<a-col :span="24">
								<a-form-item label="权限角色">
									<a-select
										placeholder="请选择权限角色"
										mode="multiple"
										v-decorator="[
                      'userRoleIList',
                      {rules: [{required: true, type: 'array', message: '请选择权限角色'}]}
                    ]"
									>
										<a-select-option v-for="item in roleList" :key="item.id">{{ item.name }}</a-select-option>
									</a-select>
								</a-form-item>
							</a-col>
							<a-col :span="24">
								<a-divider class="mt-0"/>
							</a-col>
							<a-col :span="12">
								<a-form-item label="用户昵称">
									<a-input
										placeholder="请输入用户昵称"
										:max-length="50"
										v-decorator="[
                      'nickName',
                      {rules: [{required: true, message: '请输入用户昵称', whitespace: true}]}
                    ]"
									/>
								</a-form-item>
							</a-col>
							<a-col :span="12">
								<a-form-item label="用户性别">
									<a-radio-group
										placeholder="请选择用户性别"
										v-decorator="['sex']"
									>
										<a-radio v-for="item in sexList" :key="item.value" :value="item.value">{{ item.name }}</a-radio>
									</a-radio-group>
								</a-form-item>
							</a-col>
						</a-row>
					</a-col>
					<a-col class="flex justify-center" style="align-self: stretch" :span="1">
						<a-divider style="height: 100%;" type="vertical"/>
					</a-col>
					<a-col :span="5">
						<a-form-item label="用户头像">
							<Upload @uploadSuccess="uploadAvatarSuccess">
								<section class="inline-flex flex-col items-center">
									<a-avatar class="mb-16" :size="120" :src="form.getFieldValue('imagePath') || '/avatar.png'"/>
									<a-button icon="upload">上传头像</a-button>
								</section>
							</Upload>
						</a-form-item>
					</a-col>
				</a-row>
			</a-form>
		</a-modal>
	</a-spin>
</template>
<script>
import { tableMixins } from '@/utils/mixins'
import { getUserList, getUserDetails, removeUser, setUserStop, editUser, createUser } from '@/api/user'
import { getAllRoleList } from '@/api/role'
import Upload from '@/components/Upload'
export default {
  name: 'UserManage',
  components: {Upload},
  mixins: [tableMixins],
  data() {
    return {
      showModal: false,
      loading: false,
      isEdit: false,
      searchInp: '',
      checkedKeys: [],
      selectedKeys: [],
      sexList: [],
      columns: [
        { dataIndex: 'account', title: '账号名' },
	      { dataIndex: 'nickName', title: '昵称' },
        { dataIndex: 'email', title: '邮箱' },
        { dataIndex: 'phone', title: '联系电话' },
        { dataIndex: 'lastLoginTimeStr', title: '最后登录时间' },
        { dataIndex: 'enable', title: '是否启用', scopedSlots: { customRender: 'enable' } },
        { dataIndex: 'action', width: 120, align: 'center', title: '操作', scopedSlots: { customRender: 'action' } }
      ],
      data: [],
      form: this.$form.createForm(this),
      roleList: [],
      currUser: {}
    }
  },
  watch: {
    showModal(val) {
      if (val) this.getAllRoleList()
    }
  },
  async created() {
    this.sexList = await this.$utils.getDictList('SexEnum')
    this.getData()
  },
  methods: {
    search() {
      this.pageNum = 1
      this.getData()
    },
    reset() {
      this.pageNum = 1
      this.searchInp = ''
      this.getData()
    },
    getData() {
      this.loading = true
      getUserList({
        search: this.searchInp.trim(),
        pageNo: this.pageNum,
        pageSize: this.rowsNum
      }).then(res => {
        this.data = res.items
        this.total = res.rowCount
      }).finally(() => this.loading = false)
    },
    getAllRoleList() {
      getAllRoleList().then(data => this.roleList = data)
    },
    editUser(data) {
      if (data.isSystemUser) return
      this.getAllRoleList()
      getUserDetails(data.id).then(data => {
        this.isEdit = true
        this.showModal = true
        data.userRoleIList = data.roleList.map(e => e.id)
        this.currUser = data
        this.$nextTick(() => this.form.setFieldsValue(data))
      })
    },
    uploadAvatarSuccess({path, thumbnailPath}) {
      this.form.setFieldsValue({
        imagePath: path,
        thumbnailPath
      })
    },
    removeUser(data, index) {
      if (data.isSystemUser) return
      this.$confirm({
        title: '提示',
        content: `删除该用户将会导致该用户无法使用系统。请问您确定删除该用户吗？`,
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk: () => {
          this.loading = true
          removeUser([data.id]).then(() => {
            this.$message.success('删除成功！')
            this.data.splice(index, 1)
            if (this.data.length === 0 && this.pageNum > 1) this.pageNum--
            this.getData()
          }).finally(() => this.loading = false)
        }
      })
    },
    setUserStop(data) {
      const isStop = data.isStop === 0 ? 1 : 0
      setUserStop({ id: data.id, isStop }).then(() => {
        data.isStop = isStop
      })
    },
    confirmUser() {
      this.form.validateFields((err, values) => {
        if (!err) {
          const confirmFn = this.isEdit ? editUser : createUser
          this.confirmLoading = true
          confirmFn(this.$utils.trimValue(values)).then(() => {
            this.$message.success(`${this.isEdit ? '修改' : '新增'}成功！`)
            this.cancel()
            this.getData()
          }).finally(() => this.confirmLoading = false)
        }
      })
    },
    cancel() {
      this.isEdit = false
      this.showModal = false
      this.form.resetFields()
    },
    passwordValidator(rule, value, callback) {
      let count = 0
      if (!value && this.isEdit) return callback()
      if (!value.match(/^.{6,16}$/)) return callback('密码长度6-16,至少含有数字/字母/特殊字符的任意两种,不能含有空格')
      if (value.match(/\s/)) return callback('密码长度6-16,至少含有数字/字母/特殊字符的任意两种,不能含有空格')
      if (value.match(/\d/)) {
        count++
      }
      if (value.match(/[a-zA-Z]/)) {
        count++
      }
      if (value.match(/[^\da-zA-Z^\s]/)) {
        count++
      }
      if (count >= 2) return callback()
      callback('密码长度6-16,至少含有数字/字母/特殊字符的任意两种,不能含有空格')
    },
    confirmPasswordValidator(rule, value, callback) {
      if (value !== this.form.getFieldValue('password')) return callback('两次密码不一致')
      callback()
    }
  }
}
</script>
<style scoped>
	.red {
		color: red
	}

	.gray {
		color: #999
	}
</style>
